package main

import (
	"fmt"
	"os"
	"strconv"
	"strings"

	"github.com/xuri/excelize"
)

func GetValues(mw *MyMainWindow) (newvalue map[string]string) {
	fileName := mw.prevFilePath
	xlsx, err := excelize.OpenFile(fileName) //打开所在的文件
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	myvalues := make(map[string]string)

	mw.Linefind = 0

	for count := 1; count <= xlsx.SheetCount; count++ {
		shname := "Sheet" + strconv.Itoa(xlsx.GetSheetIndex(xlsx.GetSheetName(count)))

		rows := xlsx.GetRows(shname) //j是代表第几行,row是一个[]string,存放数值

		for j := 0; j < len(rows); j++ {
			appendState := false

			for i, colCell := range rows[j] {

				if strings.Contains(colCell, mw.Keyword) {
					appendState = true
					myvalues["A"+strconv.Itoa(mw.Linefind+2)] = mw.prevFilePath
					myvalues["B"+strconv.Itoa(mw.Linefind+2)] = xlsx.GetSheetName(count)
					myvalues["C"+strconv.Itoa(mw.Linefind+2)] = strconv.Itoa(j + 1)
					myvalues[excelize.ToAlphaString(i+3)+strconv.Itoa(mw.Linefind+2)] = colCell
				}
			}

			if appendState == true {
				mw.Linefind = mw.Linefind + 1
			}

		}
	}
	return myvalues
}

func SaveDatas(values map[string]string, path string) error {
	xlsxNew := excelize.NewFile()            //新建一个xlsx文件
	xlsxNew.SetSheetName("Sheet1", "Result") //改了之后需要使用SheetX插入数据
	xlsxNew.SetCellValue("Sheet1", "A1", "原文件名")
	xlsxNew.SetCellValue("Sheet1", "B1", "原文件sheet")
	xlsxNew.SetCellValue("Sheet1", "C1", "原文件行号")
	xlsxNew.SetCellValue("Sheet1", "D1", "原文件内容")

	for k, v := range values {
		xlsxNew.SetCellValue("Sheet1", k, v)
	}
	err := xlsxNew.SaveAs(path)
	if err != nil {
		return err
	}

	return nil
}
